import {
  computed,
  defineAsyncComponent,
  defineComponent,
  inject,
  nextTick,
} from 'vue';
import {
  HolderOutlined,
  SettingOutlined,
  VerticalAlignBottomOutlined,
  VerticalAlignMiddleOutlined,
  VerticalAlignTopOutlined,
} from '@ant-design/icons-vue';
import {
  Button,
  Checkbox,
  Popover,
  TableColumnType,
  Tooltip,
} from 'ant-design-vue';
import { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface';
import { useRoute } from 'vue-router';
import { useColumnsStore } from '../../store/index';

export const ProTableColumnsOption = defineComponent({
  name: 'ProTableColumnsOption',
  setup(props) {
    const Vuedraggable = defineAsyncComponent(() => import('vuedraggable'));

    const { currentColumns, updateColumn, updateColumns, reset } =
      useColumnsStore()!;

    const disabledChecked = computed(() => {
      return (
        currentColumns.value.filter((item) => item.checked !== false).length <=
        1
      );
    });
    const paths = [
      '/statistical/dailyPaper',
      '/statistical/weeklyReport',
      '/statistical/monthlyReport',
      '/statistical/detailReport',
    ];
    const route = useRoute();
    if (paths.includes(route.path)) {
      nextTick(() => {
        updateColumn('address', { checked: false });
      });
    }

    const cols = computed(() => {
      return currentColumns.value.reduce<TableColumnType[][]>(
        (prev, cur) => {
          if (cur.hideInTable) return prev;
          if (cur.fixed === true || cur.fixed === 'left') {
            prev[0].push(cur);
          } else if (cur.fixed === 'right') {
            prev[2].push(cur);
          } else {
            prev[1].push(cur);
          }
          return prev;
        },
        [[], [], []],
      );
    });
    const descEnum = ['固定到左侧', '不固定', '固定在右侧'];

    const onChangeVisible = (e: CheckboxChangeEvent, dataIndex: string) => {
      const checked = e.target.checked;
      updateColumn(dataIndex, {
        checked,
      });
    };

    const onEnd = () => {
      updateColumns(cols.value.flat());
    };
    return () => (
      <Popover placement='bottomRight' trigger='click'>
        {{
          default: () => <SettingOutlined />,
          content: () => {
            return (
              <div>
                <div>
                  <Button type='link' size='small' onClick={reset}>
                    重置
                  </Button>
                </div>

                {cols.value?.map((col, index) => {
                  return (
                    <>
                      {!!col.length && (
                        <span class='text-[10px]  text-[#bbb] mb-2 ml-6'>
                          {descEnum[index]}
                        </span>
                      )}
                      <Vuedraggable
                        list={col}
                        itemKey='dataIndex'
                        // @ts-ignore
                        onEnd={(e) => onEnd(e, index)}
                      >
                        {{
                          // @ts-ignore
                          item: ({ element }) => {
                            return (
                              <div class='w-full text-nowrap flex items-center text-base leading-none mb-1'>
                                <HolderOutlined class='text-sm mr-3 cursor-move' />
                                <Checkbox
                                  checked={element.checked !== false}
                                  class='flex-1'
                                  disabled={
                                    disabledChecked.value &&
                                    element.checked !== false
                                  }
                                  onChange={(e) => {
                                    e.preventDefault();
                                    onChangeVisible(
                                      e,
                                      element.dataIndex as string,
                                    );
                                  }}
                                >
                                  {element.title}
                                </Checkbox>
                                {index !== 0 && (
                                  <Tooltip title={descEnum[0]}>
                                    <VerticalAlignTopOutlined
                                      class='text-primary text-xs cursor-move'
                                      onClick={(e) => {
                                        e.preventDefault();
                                        updateColumn(
                                          element.dataIndex as string,
                                          {
                                            fixed: true,
                                          },
                                        );
                                      }}
                                    />
                                  </Tooltip>
                                )}
                                {index !== 1 && (
                                  <Tooltip title={descEnum[1]}>
                                    <VerticalAlignMiddleOutlined
                                      class='text-primary text-xs cursor-move'
                                      onClick={(e) => {
                                        e.preventDefault();
                                        updateColumn(
                                          element.dataIndex as string,
                                          {
                                            fixed: false,
                                          },
                                        );
                                      }}
                                    />
                                  </Tooltip>
                                )}
                                {index !== 2 && (
                                  <Tooltip title={descEnum[2]}>
                                    <VerticalAlignBottomOutlined
                                      class='text-primary text-xs'
                                      onClick={() =>
                                        updateColumn(
                                          element.dataIndex as string,
                                          {
                                            fixed: 'right',
                                          },
                                        )
                                      }
                                    />
                                  </Tooltip>
                                )}
                              </div>
                            );
                          },
                        }}
                      </Vuedraggable>
                    </>
                  );
                })}
              </div>
            );
          },
        }}
      </Popover>
    );
  },
});
